package farmacia.gui.cadastro;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.text.MaskFormatter;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JFormattedTextField;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import java.awt.Toolkit;
import javax.swing.border.EtchedBorder;

import org.jdesktop.swingx.JXDatePicker;

import farmacia.dao.ClienteDao;
import farmacia.dao.endereco.CidadeDao;
import farmacia.dao.endereco.EmailDao;
import farmacia.dao.endereco.EstadoDao;
import farmacia.dao.endereco.email.Email;
import farmacia.entidade.endereco.Cidade;
import farmacia.entidade.endereco.Estado;
import farmacia.entidade.pessoa.Cliente;
import farmacia.valida.CustomPlainDocument;
import farmacia.valida.CustomPlainDocumentInteger;
import farmacia.valida.ValidaCampo;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.table.DefaultTableModel;
import javax.swing.border.SoftBevelBorder;
import javax.swing.border.BevelBorder;
import javax.swing.UIManager;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.Font;

public class JfCliente extends JFrame {
	
	ClienteDao listaTodos;
	ArrayList <Cliente> listaCliente ;
    private JComboBox cbEstado;
	private JPanel contentPane;
	private JTextField tFId;
	private JTextField jtNome;
	private JTextField jtRg;
	private JTextField jtEmail;
	private JTextField jtNacionalidade;
	private JTextField jtEndereco;
	private JTextField jtNumero;
	private JTextField jtComplemento;
	private JTextField jtBairro;
	private JTextField jtPesquisar;
	private JFormattedTextField ftCelular;
	private JComboBox cbECivil;
	private JFormattedTextField JfCpf;
	private JComboBox cbSpEstado;
	private JComboBox cbProvedor;
	private JComboBox cbSexo;
	private JFormattedTextField ftComercial;
	private JFormattedTextField ftCep;
	private JComboBox cbOEspedidor;
	private JComboBox cbCidade;
	
	private JFormattedTextField ftTelRes;
	private org.jdesktop.swingx.JXDatePicker jxData;
	private JTable jtCliente;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {

		try {
	
			UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
			
		} catch (Throwable e) {
			e.printStackTrace();
		}
		
		EventQueue.invokeLater(new Runnable() {
			
			public void run() {
				
				try {
				
					JfCliente frame = new JfCliente();
					
					frame.setVisible(true);
					
				} catch (Exception e) {
					e.printStackTrace();
					
				}
				
			}
		
		});
	}

	/**
	 * Create the frame.
	 * @throws ParseException 
	 */
	public JfCliente() throws ParseException {
		addWindowListener(new WindowAdapter() {
			@Override
			public void windowActivated(WindowEvent e) {
				try {
					carregaComboEstado();
				} catch (SQLException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
			}
		});
		
		setIconImage(Toolkit.getDefaultToolkit().getImage("/home/jorge/Imagens/universe.jpg"));
		setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
		setBounds(100, 100, 800, 600);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);
		
		JPanel panel = new JPanel();
		contentPane.add(panel, BorderLayout.CENTER);
		panel.setLayout(null);
		
		JPanel panel_1 = new JPanel();
		panel_1.setBorder(new EtchedBorder(EtchedBorder.RAISED, null, null));
		panel_1.setBounds(12, 0, 739, 309);
		panel.add(panel_1);
		panel_1.setLayout(null);
		
		jtNome = new JTextField(new CustomPlainDocument(),"",43);
		jtNome.setFont(new Font("Dialog", Font.PLAIN, 13));
		jtNome.setBounds(220, 29, 393, 23);
		panel_1.add(jtNome);
		jtNome.addKeyListener(new KeyAdapter() {
			
			
			@Override
			public void keyReleased(KeyEvent e) {
				
			jtNome.setText(jtNome.getText().toUpperCase());
				
			//tfNome.setText(tfNome.getText().toUpperCase());
		}
		
			
		});
		jtNome.setColumns(10);
		
		tFId = new JTextField();
		tFId.setBounds(12, 29, 70, 23);
		panel_1.add(tFId);
		tFId.setEditable(false);
		tFId.setColumns(10);
		
		JLabel jlId = new JLabel("ID");
		jlId.setBounds(12, 12, 70, 14);
		panel_1.add(jlId);
		
		JLabel JlCpf = new JLabel("CPF");
		JlCpf.setBounds(94, 12, 70, 14);
		panel_1.add(JlCpf);
		
	    JfCpf = new JFormattedTextField(new MaskFormatter("###.###.###-##"));
		JfCpf.setFont(new Font("Dialog", Font.PLAIN, 13));
		JfCpf.setBounds(94, 29, 108, 23);
		panel_1.add(JfCpf);
		
		JLabel JlNome = new JLabel("Nome");
		JlNome.setBounds(220, 12, 70, 14);
		panel_1.add(JlNome);
		
		JLabel JlEstCivil = new JLabel("Estado Civil");
		JlEstCivil.setBounds(623, 12, 91, 14);
		panel_1.add(JlEstCivil);
		
		cbECivil = new JComboBox();
		cbECivil.setFont(new Font("Dialog", Font.BOLD, 13));
		cbECivil.setBounds(623, 27, 99, 23);
		panel_1.add(cbECivil);
		cbECivil.setModel(new DefaultComboBoxModel(new String[] {"CASADO", "SOLTEIRO", "VIUVO"}));
		
		jtNacionalidade = new JTextField();
		jtNacionalidade.setFont(new Font("Dialog", Font.PLAIN, 13));
		jtNacionalidade.setBounds(570, 75, 152, 23);
		panel_1.add(jtNacionalidade);
		jtNacionalidade.setColumns(10);
		
		JLabel JlNacionalidade = new JLabel("Nacionalidade");
		JlNacionalidade.setBounds(570, 59, 108, 14);
		panel_1.add(JlNacionalidade);
		
	    cbSpEstado = new JComboBox();
	    cbSpEstado.setFont(new Font("Dialog", Font.BOLD, 13));
		cbSpEstado.setBounds(481, 73, 55, 23);
		panel_1.add(cbSpEstado);
		
		JLabel JlEstadoOrgao = new JLabel("Estado");
		JlEstadoOrgao.setBounds(481, 59, 70, 14);
		panel_1.add(JlEstadoOrgao);
		
		JLabel JlOExpedidor = new JLabel("Órgão Exp.");
		JlOExpedidor.setBounds(373, 59, 85, 14);
		panel_1.add(JlOExpedidor);
		
		cbOEspedidor = new JComboBox();
		cbOEspedidor.setFont(new Font("Dialog", Font.BOLD, 13));
		cbOEspedidor.setBounds(376, 73, 55, 23);
		panel_1.add(cbOEspedidor);
		cbOEspedidor.setModel(new DefaultComboBoxModel(new String[] {"SSP"}));
		
		jtRg = new JTextField(new CustomPlainDocumentInteger(),"",10);
		
		jtRg.setFont(new Font("Dialog", Font.PLAIN, 13));
		jtRg.setBounds(235, 75, 129, 23);
		panel_1.add(jtRg);
		jtRg.setColumns(10);
		
		JLabel lblNewLabel_2 = new JLabel("RG");
		lblNewLabel_2.setBounds(235, 59, 32, 14);
		panel_1.add(lblNewLabel_2);
		
	    cbSexo = new JComboBox();
		cbSexo.setFont(new Font("Dialog", Font.BOLD, 13));
		cbSexo.setBounds(125, 73, 108, 23);
		panel_1.add(cbSexo);
		cbSexo.setModel(new DefaultComboBoxModel(new String[] {"Masculino", "Feminino"}));
		
		JLabel JlSexo = new JLabel("Sexo");
		JlSexo.setBounds(115, 59, 43, 14);
		panel_1.add(JlSexo);
		
		jxData = new JXDatePicker( );
		jxData.setFont(new Font("Dialog", Font.PLAIN, 13));
		jxData.getEditor().setLocation(12, 0);
		jxData.setBounds(12,74, 114, 20);
		panel_1.add(jxData);
		
		
		JLabel JlNascimento = new JLabel("Data Nasc.");
		JlNascimento.setBounds(12, 59, 85, 14);
		panel_1.add(JlNascimento);
		
		JLabel JlCep = new JLabel("CEP");
		JlCep.setBounds(12, 106, 70, 14);
		panel_1.add(JlCep);
		
		ftCep = new JFormattedTextField(new MaskFormatter("##.###-###"));
		ftCep.setFont(new Font("Dialog", Font.PLAIN, 13));
		ftCep.setBounds(12, 121, 91, 23);
		panel_1.add(ftCep);
		
		JLabel JlEndereco = new JLabel("Endereço");
		JlEndereco.setBounds(125, 106, 70, 14);
		panel_1.add(JlEndereco);
		
		jtEndereco = new JTextField(new CustomPlainDocument(),"",43);
		jtEndereco.addKeyListener(new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent e) {
				jtEndereco.setText(jtEndereco.getText().toUpperCase());
			}
		});
		jtEndereco.setFont(new Font("Dialog", Font.PLAIN, 13));
		jtEndereco.setBounds(115, 121, 607, 23);
		panel_1.add(jtEndereco);
		jtEndereco.setColumns(10);
		
		jtNumero = new JTextField();
		jtNumero.setFont(new Font("Dialog", Font.PLAIN, 13));
		jtNumero.setBounds(12, 165, 55, 23);
		panel_1.add(jtNumero);
		jtNumero.setColumns(10);
		
		JLabel JlNumero = new JLabel("Nº");
		JlNumero.setBounds(12, 151, 70, 14);
		panel_1.add(JlNumero);
		
		JLabel JlComplemento = new JLabel("Complemento");
		JlComplemento.setBounds(83, 151, 114, 14);
		panel_1.add(JlComplemento);
		
		JLabel JlBairro = new JLabel("Bairro");
		JlBairro.setBounds(291, 151, 70, 14);
		panel_1.add(JlBairro);
		
		JLabel JlCidade = new JLabel("Cidade");
		JlCidade.setBounds(455, 151, 70, 14);
		panel_1.add(JlCidade);
		
		JLabel JlEstado = new JLabel("Estado");
		JlEstado.setBounds(657, 151, 70, 14);
		panel_1.add(JlEstado);
		
		 cbEstado = new JComboBox();
		 cbEstado.setFont(new Font("Dialog", Font.BOLD, 13));
		
		
		
		cbEstado.setBounds(667, 165, 55, 23);
		panel_1.add(cbEstado);
		cbEstado.setModel(new DefaultComboBoxModel(new String[] {""}));
		
		jtBairro = new JTextField(new CustomPlainDocument(),"",43);
		jtBairro.addKeyListener(new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent e) {
				jtBairro.setText(jtBairro.getText().toUpperCase());
			}
		});
		jtBairro.setFont(new Font("Dialog", Font.PLAIN, 13));
		jtBairro.setBounds(291, 165, 152, 23);
		panel_1.add(jtBairro);
		jtBairro.setColumns(10);
		
		jtComplemento = new JTextField(new CustomPlainDocument(),"",43);
		jtComplemento.addKeyListener(new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent e) {
				jtComplemento.setText(jtComplemento.getText().toUpperCase());
			}
		});
		jtComplemento.setFont(new Font("Dialog", Font.PLAIN, 13));
		jtComplemento.setBounds(83, 165, 172, 23);
		panel_1.add(jtComplemento);
		jtComplemento.setColumns(10);
		
		JLabel JlTelREs = new JLabel("Tel. Residencial");
		JlTelREs.setBounds(12, 204, 124, 14);
		panel_1.add(JlTelREs);
		
		JLabel JlTelCom = new JLabel("Tel. Comercial");
		JlTelCom.setBounds(178, 204, 99, 14);
		panel_1.add(JlTelCom);
		
		JLabel JlTelCel = new JLabel("Tel. Celular");
		JlTelCel.setBounds(327, 204, 85, 14);
		panel_1.add(JlTelCel);
		
		JLabel JlEmail = new JLabel("E-mail");
		JlEmail.setBounds(468, 204, 70, 14);
		panel_1.add(JlEmail);
		
		cbProvedor = new JComboBox();
		cbProvedor.setFont(new Font("Dialog", Font.BOLD, 13));
		cbProvedor.setEditable(true);
		cbProvedor.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				
			   if(e.getSource()==cbProvedor)
			   {
				   try {
					listaEmailBox();
				} catch (SQLException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				   
			   }
			}
		});
		cbProvedor.setBounds(598, 228, 114, 23);
		panel_1.add(cbProvedor);
		
		jtEmail = new JTextField();
		jtEmail.setFont(new Font("Dialog", Font.PLAIN, 13));
		jtEmail.setBounds(468, 230, 124, 23);
		panel_1.add(jtEmail);
		jtEmail.setColumns(10);
		
		ftCelular = new JFormattedTextField(new MaskFormatter("(##)####-####"));
		ftCelular.setFont(new Font("Dialog", Font.PLAIN, 13));
		ftCelular.setBounds(329, 230, 99, 23);
		panel_1.add(ftCelular);
		
		ftComercial = new JFormattedTextField(new MaskFormatter("(##)####-####"));
		ftComercial.setFont(new Font("Dialog", Font.PLAIN, 13));
		ftComercial.setBounds(178, 230, 99, 23);
		panel_1.add(ftComercial);
		
		ftTelRes = new JFormattedTextField(new MaskFormatter("(##)####-####"));
		ftTelRes.setFont(new Font("Dialog", Font.PLAIN, 13));
		ftTelRes.setBounds(12, 230, 99, 23);
		panel_1.add(ftTelRes);
		
		jtPesquisar = new JTextField();
		jtPesquisar.addKeyListener(new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent e) {
				jtPesquisar.setText(jtPesquisar.getText().toUpperCase());
			}
		});
		jtPesquisar.setFont(new Font("Dialog", Font.PLAIN, 13));
		jtPesquisar.setBounds(12, 279, 384, 23);
		panel_1.add(jtPesquisar);
		jtPesquisar.setColumns(10);
		
		JButton btnPesquisar = new JButton("Pesquisar");
		btnPesquisar.setBounds(408, 276, 117, 24);
		panel_1.add(btnPesquisar);
		
		cbCidade = new JComboBox();
		cbCidade.setFont(new Font("Dialog", Font.BOLD, 13));
		cbCidade.setBounds(455, 165, 172, 23);
		panel_1.add(cbCidade);
		
		JLabel JlProvedor = new JLabel("Provedor");
		JlProvedor.setBounds(598, 204, 70, 14);
		panel_1.add(JlProvedor);
		
		JPanel panel_2 = new JPanel();
		panel_2.setBorder(new EtchedBorder(EtchedBorder.LOWERED, null, null));
		panel_2.setBounds(12, 321, 739, 31);
		panel.add(panel_2);
		panel_2.setLayout(null);
		
		JButton btnNovo = new JButton("Novo");
		btnNovo.addKeyListener(new KeyAdapter() {
			@Override
			public void keyReleased(KeyEvent e) {
			  Cliente n1 = new Cliente();
			  
			}
		});
		btnNovo.setBounds(12, 3, 116, 24);
		panel_2.add(btnNovo);
		
		JButton btnAlterar = new JButton("Alterar");
		btnAlterar.setBounds(164, 3, 117, 24);
		panel_2.add(btnAlterar);
		
		JButton btnExcluir = new JButton("Excluir");
		btnExcluir.setBounds(331, 3, 117, 24);
		panel_2.add(btnExcluir);
		
		JButton btnSalvar = new JButton("Salvar");
		btnSalvar.setBounds(483, 3, 117, 24);
		panel_2.add(btnSalvar);
		
		jtCliente = new JTable();
		jtCliente.setBorder(new SoftBevelBorder(BevelBorder.LOWERED, null, null, null, null));
		
		jtCliente.setModel(new DefaultTableModel(
			new Object[][] {
				{null, null},
				{null, null},
				{null, null},
				{null, null},
				{null, null},
				{null, null},
			},
			new String[] {
				"CPF", "Nome"
			}
		));
		jtCliente.getColumnModel().getColumn(1).setPreferredWidth(458);
		jtCliente.setBounds(22, 368, 733, 170);
		panel.add(jtCliente);
		
		
	}
	
	/*
	private void salvarSubstancia() throws SQLException{
		PessoaFisica pessoa = new PessoaFisica();
		
		pessoa.setNome(this.tfNome.getText());
		suthis.tfSubstancia.getText());
		
		PessoaFisicaDao dao = new PessoaFisicaDao();
		dao.adicionar(sub);
		
		
	}
	*/
	private void listaEmailBox() throws SQLException{
		
		cbProvedor.removeAll();
		//cbEmail.addItem("");
		
		EmailDao email= new EmailDao();
		List<Email>lista = email.getLista();
		
		Iterator<Email>it = lista.iterator();
		
		while(it.hasNext())
		{
			Email e = it.next();
			String emails = e.getFi_eMail();
			cbProvedor.addItem(emails);
			
		}
	}
/*	private void alterarCliente() throws SQLException{
        if(jTTabela.getSelectedRow()!=-1){
            if(validaCampo()){
            Cliente c = new Cliente();
            ClienteDao cl = new ClienteDao();
              
              c.setNome(jtNome.getText());
              c.setEnderecoPessoa(jTEndereco.getText());
              c.setCpfPessoa(Long.parseLong(jTCpf.getText()));
              c.setRgPessoa(Integer.parseInt(jTRg.getText()));
              c.setCidadePessoa(jCBCidade.getSelectedItem().toString());
              c.setCepPessoa(Integer.parseInt(jTCep.getText()));
              c.setCompEnderecoPessoa(jTCompEndereco.getText());
              c.setEstCivilPessoa(jCBEstCivil.getSelectedItem().toString());           
              c.setEstadoCidPessoa(jCEstado.getSelectedItem().toString());
              c.setBairroPessoa(jTBairro.getText());
              c.setCodPessoa(Integer.parseInt(jTFCodCliente.getText()));
            cl.alterar(c);
            JOptionPane.showMessageDialog(null, "Cliente alterado com sucesso");
            }
        }*/
	
	
	private boolean validaCampo(){
		if(!jtNome.getText().equals("")
			&& ! jtBairro.getText().equals("")
			&& ! cbEstado.getSelectedItem().equals("")
			&& ! jtComplemento.getText().equals("")
			&& ! jtNacionalidade.getText().equals("")
			&& ! jtNumero.getText().equals("")){
				return true;
				
				
			}else{
				JOptionPane.showMessageDialog(rootPane, "Existem Campos em branco");
			}
			return false;
		
		
	}
	private void jBNovo(java.awt.event.ActionEvent evt) {                        
        abilitaDados();//limpar campo
        try {
        	this.jtNome.setText("");
        	this.tFId.setText("");
        	this.JfCpf.setText("");
        	this.cbECivil.setSelectedIndex(0);
        	this.cbSpEstado.setSelectedIndex(0);
        	this.cbOEspedidor.setSelectedIndex(0);
        	this.jtRg.setText("");
        	this.cbSexo.setSelectedIndex(0);
        	this.ftCep.setText("");
        	this.jtEndereco.setText("");
        	this.jtNumero.setText("");
        	this.cbEstado.setSelectedIndex(0);
        	this.jtBairro.setText("");
        	this.jtComplemento.setText("");
        	this.cbProvedor.setSelectedIndex(0);
        	this.jtEmail.setText("");
        	this.ftCelular.setText("");
        	this.ftComercial.setText("");
        	this.ftTelRes.setText("");
        	this.jtPesquisar.setText("");
        	
        	
        } catch (Exception e) {
            JOptionPane.showMessageDialog(rootPane, "Erro ao limpar campos" + e);
        }

	}     

       private void desabilita (){
        this.jtNome.setEditable(false);            	
       	this.JfCpf.setEditable(false);
       	this.cbECivil.setEditable(false);
       	this.cbSpEstado.setEditable(false);
       	this.cbOEspedidor.setEditable(false);
       	this.jtRg.setEditable(false);
       	this.cbSexo.setEditable(false);
       	this.ftCep.setEditable(false);
       	this.jtEndereco.setEditable(false);
       	this.jtNumero.setEditable(false);
       	this.cbEstado.setEditable(false);
       	this.jtBairro.setEditable(false);
       	this.jtComplemento.setEditable(false);
       	this.cbProvedor.setEditable(false);
       	this.jtEmail.setEditable(false);
       	this.ftCelular.setEditable(false);
       	this.ftComercial.setEditable(false);
       	this.ftTelRes.setEditable(false);
       	this.jtPesquisar.setEditable(false);
       
       }
       /*
       
        * Meto que abilita a digitação de dados apos clicar no botao de novo
       
        **/

       private void abilitaDados(){
    	   this.jtNome.setEditable(true);            	
          	this.JfCpf.setEditable(true);
          	this.cbECivil.setEditable(true);
          	this.cbSpEstado.setEditable(true);
          	this.cbOEspedidor.setEditable(true);
          	this.jtRg.setEditable(true);
          	this.cbSexo.setEditable(true);
          	this.ftCep.setEditable(true);
          	this.jtEndereco.setEditable(true);
          	this.jtNumero.setEditable(true);
          	this.cbEstado.setEditable(true);
          	this.jtBairro.setEditable(true);
          	this.jtComplemento.setEditable(true);
          	this.cbProvedor.setEditable(true);
          	this.jtEmail.setEditable(true);
          	this.ftCelular.setEditable(true);
          	this.ftComercial.setEditable(true);
          	this.ftTelRes.setEditable(true);
          	this.jtPesquisar.setEditable(true);
       }


                 
	public void carregaComboEstado() throws SQLException
	{
		
		EstadoDao dao;  
        try {  
            dao = new EstadoDao();  
            List<Estado> minhalista = dao.getLista();  
            for (int i = 0; i < minhalista.size(); i++) {  
                cbEstado.addItem(minhalista.get(i).getFi_abreviatura());
                cbSpEstado.addItem(minhalista.get(i).getFi_abreviatura());
                
            }  
            cbEstado = new JComboBox();  
        } catch (SQLException ex) {  
            JOptionPane.showMessageDialog(null,"Erro  ! " + ex);  
        }  
	  
	    }  
	public void carregaComboCidade() throws SQLException
	{
		
		CidadeDao dao;  
        try {  
            dao = new CidadeDao();  
            List<Cidade> minhalista = dao.getLista();  
            for (int i = 0; i < minhalista.size(); i++) {  
                cbEstado.addItem(minhalista.get(i).getFi_abreviatura());
                cbSpEstado.addItem(minhalista.get(i).getFi_abreviatura());
                
            }  
            cbEstado = new JComboBox();  
        } catch (SQLException ex) {  
            JOptionPane.showMessageDialog(null,"Erro  ! " + ex);  
        }  
	  
	    }  
}
